
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file was initially generated by gen_to_start.go (add link), as a start
// of the Traffic Ops golang data model

package api

import (
	"encoding/json"
	_ "github.com/apache/trafficcontrol/traffic_ops/experimental/server/output_format" // needed for swagger
	"github.com/jmoiron/sqlx"
	null "gopkg.in/guregu/null.v3"
	"log"
	"time"
)

type Deliveryservices struct {
	Name                 string                `db:"name" json:"name"`
	DisplayName          string                `db:"display_name" json:"displayName"`
	Description          string                `db:"description" json:"description"`
	Active               bool                  `db:"active" json:"active"`
	Dscp                 int64                 `db:"dscp" json:"dscp"`
	Signed               bool                  `db:"signed" json:"signed"`
	QstringIgnore        bool                  `db:"qstring_ignore" json:"qstringIgnore"`
	GeoLimit             bool                  `db:"geo_limit" json:"geoLimit"`
	HttpBypassFqdn       null.String           `db:"http_bypass_fqdn" json:"httpBypassFqdn"`
	DnsBypassIp          null.String           `db:"dns_bypass_ip" json:"dnsBypassIp"`
	DnsBypassIp6         null.String           `db:"dns_bypass_ip6" json:"dnsBypassIp6"`
	DnsBypassTtl         null.Int              `db:"dns_bypass_ttl" json:"dnsBypassTtl"`
	OrgServerFqdn        null.String           `db:"org_server_fqdn" json:"orgServerFqdn"`
	DnsTtl               null.Int              `db:"dns_ttl" json:"dnsTtl"`
	GlobalMaxMbps        null.Int              `db:"global_max_mbps" json:"globalMaxMbps"`
	GlobalMaxTps         null.Int              `db:"global_max_tps" json:"globalMaxTps"`
	MaxDnsAnswers        null.Int              `db:"max_dns_answers" json:"maxDnsAnswers"`
	InfoUrl              null.String           `db:"info_url" json:"infoUrl"`
	MissLat              null.Int              `db:"miss_lat" json:"missLat"`
	MissLong             null.Int              `db:"miss_long" json:"missLong"`
	CheckPath            null.String           `db:"check_path" json:"checkPath"`
	Protocol             null.Int              `db:"protocol" json:"protocol"`
	SslKeyVersion        null.Int              `db:"ssl_key_version" json:"sslKeyVersion"`
	Ipv6RoutingEnabled   bool                  `db:"ipv6_routing_enabled" json:"ipv6RoutingEnabled"`
	RangeRequestHandling null.Int              `db:"range_request_handling" json:"rangeRequestHandling"`
	EdgeHeaderRewrite    null.String           `db:"edge_header_rewrite" json:"edgeHeaderRewrite"`
	OriginShield         null.String           `db:"origin_shield" json:"originShield"`
	MidHeaderRewrite     null.String           `db:"mid_header_rewrite" json:"midHeaderRewrite"`
	RegexRemap           null.String           `db:"regex_remap" json:"regexRemap"`
	Cacheurl             null.String           `db:"cacheurl" json:"cacheurl"`
	RemapText            null.String           `db:"remap_text" json:"remapText"`
	MultiSiteOrigin      null.Bool             `db:"multi_site_origin" json:"multiSiteOrigin"`
	TrResponseHeaders    null.String           `db:"tr_response_headers" json:"trResponseHeaders"`
	InitialDispersion    int64                 `db:"initial_dispersion" json:"initialDispersion"`
	DnsBypassCname       null.String           `db:"dns_bypass_cname" json:"dnsBypassCname"`
	TrRequestHeaders     null.String           `db:"tr_request_headers" json:"trRequestHeaders"`
	CreatedAt            time.Time             `db:"created_at" json:"createdAt"`
	Links                DeliveryservicesLinks `json:"_links" db:-`
}

type DeliveryservicesLinks struct {
	Self                      string                    `db:"self" json:"_self"`
	CdnsLink                  CdnsLink                  `json:"cdns" db:-`
	DomainsLink               DomainsLink               `json:"domains" db:-`
	DeliveryservicesTypesLink DeliveryservicesTypesLink `json:"deliveryservices_types" db:-`
	ProfilesLink              ProfilesLink              `json:"profiles" db:-`
}

// @Title getDeliveryservicesById
// @Description retrieves the deliveryservices information for a certain id
// @Accept  application/json
// @Param   id              path    int     false        "The row id"
// @Success 200 {array}    Deliveryservices
// @Resource /api/2.0
// @Router /api/2.0/deliveryservices/{id} [get]
func getDeliveryservice(name string, db *sqlx.DB) (interface{}, error) {
	ret := []Deliveryservices{}
	arg := Deliveryservices{}
	arg.Name = name
	queryStr := "select *, concat('" + API_PATH + "deliveryservices/', name) as self"
	queryStr += ", concat('" + API_PATH + "cdns/', cdn) as cdns_name_ref"
	queryStr += ", concat('" + API_PATH + "domains/', domain) as domains_name_ref"
	queryStr += ", concat('" + API_PATH + "deliveryservices_types/', type) as deliveryservices_types_name_ref"
	queryStr += ", concat('" + API_PATH + "profiles/', profile) as profiles_name_ref"
	queryStr += " from deliveryservices WHERE name=:name"
	nstmt, err := db.PrepareNamed(queryStr)
	err = nstmt.Select(&ret, arg)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	nstmt.Close()
	return ret, nil
}

// @Title getDeliveryservicess
// @Description retrieves the deliveryservices
// @Accept  application/json
// @Success 200 {array}    Deliveryservices
// @Resource /api/2.0
// @Router /api/2.0/deliveryservices [get]
func getDeliveryservices(db *sqlx.DB) (interface{}, error) {
	ret := []Deliveryservices{}
	queryStr := "select *, concat('" + API_PATH + "deliveryservices/', name) as self"
	queryStr += ", concat('" + API_PATH + "cdns/', cdn) as cdns_name_ref"
	queryStr += ", concat('" + API_PATH + "domains/', domain) as domains_name_ref"
	queryStr += ", concat('" + API_PATH + "deliveryservices_types/', type) as deliveryservices_types_name_ref"
	queryStr += ", concat('" + API_PATH + "profiles/', profile) as profiles_name_ref"
	queryStr += " from deliveryservices"
	err := db.Select(&ret, queryStr)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return ret, nil
}

// @Title postDeliveryservices
// @Description enter a new deliveryservices
// @Accept  application/json
// @Param                 Body body     Deliveryservices   true "Deliveryservices object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/deliveryservices [post]
func postDeliveryservice(payload []byte, db *sqlx.DB) (interface{}, error) {
	var v Deliveryservices
	err := json.Unmarshal(payload, &v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "INSERT INTO deliveryservices("
	sqlString += "name"
	sqlString += ",display_name"
	sqlString += ",description"
	sqlString += ",cdn"
	sqlString += ",domain"
	sqlString += ",active"
	sqlString += ",dscp"
	sqlString += ",signed"
	sqlString += ",qstring_ignore"
	sqlString += ",geo_limit"
	sqlString += ",http_bypass_fqdn"
	sqlString += ",dns_bypass_ip"
	sqlString += ",dns_bypass_ip6"
	sqlString += ",dns_bypass_ttl"
	sqlString += ",org_server_fqdn"
	sqlString += ",type"
	sqlString += ",profile"
	sqlString += ",dns_ttl"
	sqlString += ",global_max_mbps"
	sqlString += ",global_max_tps"
	sqlString += ",max_dns_answers"
	sqlString += ",info_url"
	sqlString += ",miss_lat"
	sqlString += ",miss_long"
	sqlString += ",check_path"
	sqlString += ",protocol"
	sqlString += ",ssl_key_version"
	sqlString += ",ipv6_routing_enabled"
	sqlString += ",range_request_handling"
	sqlString += ",edge_header_rewrite"
	sqlString += ",origin_shield"
	sqlString += ",mid_header_rewrite"
	sqlString += ",regex_remap"
	sqlString += ",cacheurl"
	sqlString += ",remap_text"
	sqlString += ",multi_site_origin"
	sqlString += ",tr_response_headers"
	sqlString += ",initial_dispersion"
	sqlString += ",dns_bypass_cname"
	sqlString += ",tr_request_headers"
	sqlString += ",created_at"
	sqlString += ") VALUES ("
	sqlString += ":name"
	sqlString += ",:display_name"
	sqlString += ",:description"
	sqlString += ",:cdn"
	sqlString += ",:domain"
	sqlString += ",:active"
	sqlString += ",:dscp"
	sqlString += ",:signed"
	sqlString += ",:qstring_ignore"
	sqlString += ",:geo_limit"
	sqlString += ",:http_bypass_fqdn"
	sqlString += ",:dns_bypass_ip"
	sqlString += ",:dns_bypass_ip6"
	sqlString += ",:dns_bypass_ttl"
	sqlString += ",:org_server_fqdn"
	sqlString += ",:type"
	sqlString += ",:profile"
	sqlString += ",:dns_ttl"
	sqlString += ",:global_max_mbps"
	sqlString += ",:global_max_tps"
	sqlString += ",:max_dns_answers"
	sqlString += ",:info_url"
	sqlString += ",:miss_lat"
	sqlString += ",:miss_long"
	sqlString += ",:check_path"
	sqlString += ",:protocol"
	sqlString += ",:ssl_key_version"
	sqlString += ",:ipv6_routing_enabled"
	sqlString += ",:range_request_handling"
	sqlString += ",:edge_header_rewrite"
	sqlString += ",:origin_shield"
	sqlString += ",:mid_header_rewrite"
	sqlString += ",:regex_remap"
	sqlString += ",:cacheurl"
	sqlString += ",:remap_text"
	sqlString += ",:multi_site_origin"
	sqlString += ",:tr_response_headers"
	sqlString += ",:initial_dispersion"
	sqlString += ",:dns_bypass_cname"
	sqlString += ",:tr_request_headers"
	sqlString += ",:created_at"
	sqlString += ")"
	result, err := db.NamedExec(sqlString, v)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}

// @Title putDeliveryservices
// @Description modify an existing deliveryservicesentry
// @Accept  application/json
// @Param   id              path    int     true        "The row id"
// @Param                 Body body     Deliveryservices   true "Deliveryservices object that should be added to the table"
// @Success 200 {object}    output_format.ApiWrapper
// @Resource /api/2.0
// @Router /api/2.0/deliveryservices/{id}  [put]
func putDeliveryservice(name string, payload []byte, db *sqlx.DB) (interface{}, error) {
	var arg Deliveryservices
	err := json.Unmarshal(payload, &arg)
	arg.Name = name
	if err != nil {
		log.Println(err)
		return nil, err
	}
	sqlString := "UPDATE deliveryservices SET "
	sqlString += "name = :name"
	sqlString += ",display_name = :display_name"
	sqlString += ",description = :description"
	sqlString += ",cdn = :cdn"
	sqlString += ",domain = :domain"
	sqlString += ",active = :active"
	sqlString += ",dscp = :dscp"
	sqlString += ",signed = :signed"
	sqlString += ",qstring_ignore = :qstring_ignore"
	sqlString += ",geo_limit = :geo_limit"
	sqlString += ",http_bypass_fqdn = :http_bypass_fqdn"
	sqlString += ",dns_bypass_ip = :dns_bypass_ip"
	sqlString += ",dns_bypass_ip6 = :dns_bypass_ip6"
	sqlString += ",dns_bypass_ttl = :dns_bypass_ttl"
	sqlString += ",org_server_fqdn = :org_server_fqdn"
	sqlString += ",type = :type"
	sqlString += ",profile = :profile"
	sqlString += ",dns_ttl = :dns_ttl"
	sqlString += ",global_max_mbps = :global_max_mbps"
	sqlString += ",global_max_tps = :global_max_tps"
	sqlString += ",max_dns_answers = :max_dns_answers"
	sqlString += ",info_url = :info_url"
	sqlString += ",miss_lat = :miss_lat"
	sqlString += ",miss_long = :miss_long"
	sqlString += ",check_path = :check_path"
	sqlString += ",protocol = :protocol"
	sqlString += ",ssl_key_version = :ssl_key_version"
	sqlString += ",ipv6_routing_enabled = :ipv6_routing_enabled"
	sqlString += ",range_request_handling = :range_request_handling"
	sqlString += ",edge_header_rewrite = :edge_header_rewrite"
	sqlString += ",origin_shield = :origin_shield"
	sqlString += ",mid_header_rewrite = :mid_header_rewrite"
	sqlString += ",regex_remap = :regex_remap"
	sqlString += ",cacheurl = :cacheurl"
	sqlString += ",remap_text = :remap_text"
	sqlString += ",multi_site_origin = :multi_site_origin"
	sqlString += ",tr_response_headers = :tr_response_headers"
	sqlString += ",initial_dispersion = :initial_dispersion"
	sqlString += ",dns_bypass_cname = :dns_bypass_cname"
	sqlString += ",tr_request_headers = :tr_request_headers"
	sqlString += ",created_at = :created_at"
	sqlString += " WHERE name=:name"
	result, err := db.NamedExec(sqlString, arg)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}

// @Title delDeliveryservicesById
// @Description deletes deliveryservices information for a certain id
// @Accept  application/json
// @Param   id              path    int     false        "The row id"
// @Success 200 {array}    Deliveryservices
// @Resource /api/2.0
// @Router /api/2.0/deliveryservices/{id} [delete]
func delDeliveryservice(name string, db *sqlx.DB) (interface{}, error) {
	arg := Deliveryservices{}
	arg.Name = name
	result, err := db.NamedExec("DELETE FROM deliveryservices WHERE name=:name", arg)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return result, err
}
